﻿var canvas = new fabric.Canvas('c');
this.__canvas = canvas;
fabric.Object.prototype.selectable = true;
var cboStyle = document.getElementById('cbo-style');
var cboColor = document.getElementById('cbo-color');
var cboGem = document.getElementById('cbo-gem');
var chkRecommend = document.getElementById('chk-recommend');

canvas.on('mouse:down', function (options) {
    var x = options.e.offsetX;
    var y = options.e.offsetY;   
    console.log('x: ' + x + ', y: ' + y);
});
var areaWidth = 425;
var areaHeight = 480;
fabric.Image.fromURL(EarPosition[0][0], function (oImg) {
                        oImg.selectable = false; 
                        oImg.scaleToWidth(areaWidth);
                        canvas.add(oImg);
                        oImg.center();
                        canvas.sendToBack(oImg);
});
//{x: 170, y:287}
//{x: 387, y:287}

//{x: 82, y: 80}
//Left ของจู๊บคือ Right ของเหม่ง
var tempArray = [];

function tryEarring(erLeft, erRight, code, styleName) {
    if (!checkDuplicateCapture(code)) return;

    var folder = styleName;
    clearOld();
    tempArray = [];

    var tempRight = EarPosition[0][1];
    var rightX = parseInt(tempRight.split(',')[0]);
    var rightY = parseInt(tempRight.split(',')[1]);

    var tempLeft = EarPosition[0][2];
    var leftX = parseInt(tempLeft.split(',')[0]);
    var leftY = parseInt(tempLeft.split(',')[1]);

    var earPosition;
    for (var i = 0; i < EarringsSuggest[0].length; i++) {
        if (code === EarringsSuggest[0][i].Er_Code) {
            earPosition = EarringsSuggest[0][i];
            break;
        }
    }
    var earPosRight = earPosition.Er_Back_Right;
    var earPosRX = parseInt(earPosRight.split(',')[0]);
    var earPosRY = parseInt(earPosRight.split(',')[1]);

    var earPosLeft = earPosition.Er_Back_Left;
    var earPosLX = parseInt(earPosLeft.split(',')[0]);
    var earPosLY = parseInt(earPosLeft.split(',')[1]);

    var cdWidth = CDWidth[0];
    var ratio = 0.18 * cdWidth / 92; //0.24;
    fabric.Image.fromURL('data/earrings/' + folder + '/' + erLeft, function (oImg) {
        canvas.add(oImg);
        //oImg.set({ left: rightX - (earPosLX * ratio) + 8, top: rightY - (earPosLY * ratio) + 8, scaleX: ratio, scaleY: ratio, er_code: code });
        oImg.set({ left: rightX - (earPosLX * ratio) + 9, top: rightY - (earPosLY * ratio) + 9, scaleX: ratio, scaleY: ratio, er_code: code });
        oImg.setCoords();
        canvas.bringToFront(oImg);
        tempArray.push(oImg);
    });
   
    fabric.Image.fromURL('data/earrings/' + folder + '/' + erRight, function (oImg) {
        canvas.add(oImg);
        //oImg.set({ left: leftX - (earPosRX * ratio) + 8, top: leftY - (earPosRY * ratio) + 8, scaleX: ratio, scaleY: ratio, er_code: code });
        oImg.set({ left: leftX - (earPosRX * ratio) +9 , top: leftY - (earPosRY * ratio) + 9 , scaleX: ratio, scaleY: ratio, er_code: code });
        oImg.setCoords();
        canvas.bringToFront(oImg);
        tempArray.push(oImg);
    });

    canvas.renderAll();
}
canvas.renderAll();

function checkDuplicateCapture(er_code) {
    var img = $('.img-compare');
    var rtn = true;
    for (var i = 0; i < img.length; i++) {
        if (img[i].getAttribute('er_code') === er_code) {
            rtn = false;
            break;
        }        
    }

    return rtn;
}


function clearOld() {
    for (var i = 0; i < tempArray.length; i++) {
        canvas.remove(tempArray[i]);
    }
    canvas.renderAll();
}

var captureCount = 0;
var btnCapture = document.getElementById('btn-capture');
btnCapture.onclick = function () {
    if (captureCount === 4) {
        Toast.init({
            "selector": ".alert-warning"
        });
        Toast.show("ท่านสามารถลองและเปรียบเทียบต่างหูได้สูงสุดครั้งละ 4 คู่ !!!");
        return;
    }
    if (!checkDuplicateCapture(tempArray[0].er_code)) {
        Toast.init({
            "selector": ".alert-warning"
        });
        Toast.show("ต่างหูคู่นี้ได้ถูกเก็บภาพไว้แล้ว !!!");
        return;        
    }

    if (tempArray.length <= 0) {
        Toast.init({
            "selector": ".alert-warning"
        });
        Toast.show("ท่านยังไม่ได้เลือกต่างหูที่ต้องการจะลอง !!!");
        return;
    }
    canvas.deactivateAll();
    var url = canvas.toDataURL();

    //create new image;
    var img = new Image();
    img.onload = function() {
        img.style.width = '210px';
        img.className = 'img-thumbnail img-compare';
        img.style.cursor = 'pointer';
    }
    img.src = url;
    img.setAttribute('er_code', tempArray[0].er_code);

    img.onclick = function() {
        bootbox.dialog({
             message: '<img class="img-thumbnail" style="height: 500px;" src=' + this.src + '>'
         });//boobox
    }

    var listCapture = document.getElementById('list-capture');
    var closeButton = '<button type="button" class="close" aria-label="Close"><span aria-hidden="true">&times;</span></button>';
    var div = document.createElement('div');
    div.style.width = '210px';
    div.innerHTML += closeButton;
    div.appendChild(img);    
    listCapture.appendChild(div);

    captureCount++;
}

$(document).on('click', '.close', function() {
    $(this).parent().remove();
    captureCount--;
});

var btnAddToCart = document.getElementById('btn-addtocart');
btnAddToCart.onclick = function () {
    if (tempArray.length <= 0) {
        Toast.init({
            "selector": ".alert-warning"
        });
        Toast.show("ท่านยังไม่ได้เลือกต่างหูที่ต้องการจะสั่ง !!!");
        return;
    }

    var er_code = tempArray[0].er_code;
    var qty = 1;
    //call ajax
    $.ajax({
        type: "POST",
        dataType: "json",
        crossDomain: true,
        url: "http://localhost:49331/WSRestFul.asmx/RecalQty",
        data: { ERCode: er_code, Qty: qty }
    }) //ajax
    .done(function (data) {
        if (data.result === 'success') {
            Toast.init({
                "selector": ".alert-success"
            });
            Toast.show("เพิ่มต่างหูเข้าตะกร้าสินค้าของท่านแล้ว");

            var tmp = parseInt($('span.badge').html());
            tmp++;
            $('span.badge').html(tmp);
        }
    }) //done
    .fail(function (data) {
        bootbox.dialog({
            title: 'Fatal Error',
            message: '<div class="alert alert-danger" role="alert"><strong>Error in connection !!!</strong></div>'
        });//boobox
    }) //fail
}

cboStyle.onchange = function() {
    filterEarring();
}
cboColor.onchange = function () {
    filterEarring();
}
cboGem.onchange = function () {
    filterEarring();
}
chkRecommend.onchange = function () {
    filterEarring();
}

$(document).ready(function() {
    if (EarringsStyles) {        
        cboStyle.innerHTML = '<option value="All">Style</option>';
        EarringsStyles[0].forEach(function(item) {
            cboStyle.innerHTML += '<option value="' + item.StyleId + '|' + item.StyleName + '">' + item.StyleName + '</option>';
        });
        $(cboStyle).selectpicker();
    }

    if (EarringsColor) {
        cboColor.innerHTML = '<option value="All">Color</option>';
        EarringsColor[0].forEach(function(item) {
            cboColor.innerHTML += '<option value="' + item.ColorId + '|' + item.ColorName + '" data-content="<div style=\'width:100%;\'><img style=\'width:15px;\' src=\'' + item.ColorImgName + '\' ><span class=\'pull-right\' style=\'margin-top:-3px;\'>' + item.ColorName + '</span></div> " >' + item.ColorName + '</option>';
        });
        $(cboColor).selectpicker();
    }

    if (EarringsGemstone) {
        cboGem.innerHTML = '<option value="All">Gem</option>';
        EarringsGemstone[0].forEach(function (item) {
            cboGem.innerHTML += '<option value="' + item.Gemstone + '|' + item.Gemstone + '">' + item.Gemstone + '</option>';
        });
        $(cboGem).selectpicker();
    }    

    filterEarring();
    $('#face-shape-text').html('ลักษณะใบหน้าของคุณคือ ' + Faceshape[0] + '&nbsp;&nbsp;' + '<a id="more-detail" href="#" >ดูรายละเอียดเพิ่มเติม</a>');

    $('#more-detail').click(function () {
        var message = DescriptionMessage[0];
        bootbox.alert({
            title: 'รายละเอียดเพิ่มเติม',
            message: message
        });
    });
});



function filterEarring() {   

    var styleId = cboStyle.value.split('|')[0];
    //var styleName = cboStyle.value.split('|')[1];

    var colorId = cboColor.value.split('|')[0];
    var gemStone = cboGem.value.split('|')[0];

    var listEr = document.getElementById('er-list');
    listEr.innerHTML = '';

    EarringsSuggest[0].forEach(function(earring) {
        var condition1 = false;
        if (styleId != 'All') {
            condition1 = (earring.Er_Style === styleId);
        } else {
            condition1 = true;
        }
        var condition2 = false;
        if (colorId != 'All') {
            condition2 = (earring.Er_Color === colorId);
        } else {
            condition2 = true;
        }
        var condition3 = false;
        if (gemStone != 'All') {
            condition3 = (earring.Er_Gemstone === gemStone);
        } else {
            condition3 = true;
        }
       
        if (condition1 && condition2 && condition3) {

            if (chkRecommend.checked && earring.Suggest === 'True') {
                addEarringsToList(listEr, earring);
            } else if (!chkRecommend.checked) {
                addEarringsToList(listEr, earring);
            }            
        }
    });

    //$('h4').wrapInner('<span>')

    $('h4 br')
        .before("<span class='spacer'>&nbsp;</span>")
        .after("<span class='spacer'>&nbsp;</span>");
}

function addEarringsToList(listEr, earring) {
    var img = new Image();
    img.onload = function () {
        img.style.width = "150px;";
        img.className = 'img-thumbnail';
        img.style.cursor = 'pointer';
        img.title = 'ลองต่างหู';
    }
    var styleName = earring.StyleName;
    var url = 'data/earrings/' + styleName + '/' + earring.Er_Image_Front;
    img.src = url;

    img.onclick = function () {
        tryEarring(earring.Er_Image_Left, earring.Er_Image_Right, earring.Er_Code, styleName);
    };

    var div = document.createElement('div');
    div.style.width = '150px';
    div.className = 'image';
    div.appendChild(img);
    var spanClassName = 'normal-earrings';
    if (earring.Suggest === 'True') {
        spanClassName = 'suggest-earrings';

        //var text = document.createElement('h4');        
        var span = document.createElement('span');
        span.className = 'glyphicon glyphicon-heart suggest-heart';
        //if (earring.Suggest === 'True') {
        //    span.className = 'suggest-earrings';
        //}
        //var spanClassName = span.className;
        //span.innerHTML = earring.Er_Name;
        //text.appendChild(span);    
        //div.appendChild(text);
        div.appendChild(span);
    }

    var spanMagnifier = document.createElement('span');
    spanMagnifier.className = 'magnifier glyphicon glyphicon-zoom-in';
    spanMagnifier.style.cursor = 'pointer';
    spanMagnifier.title = 'รูปขยาย';
    div.appendChild(spanMagnifier);
    spanMagnifier.onclick = function () {
        var htmlText = '<div class="image">';
        htmlText += '<img class="img-thumbnail" style="height: 500px;" src=' + url + '>';
        htmlText += '<h4 class="img-magnifier"><span class="'+spanClassName+'">'+earring.Er_ShortName+'</span></h4>';
        htmlText += '</div>';

        bootbox.dialog({
            message: htmlText
        });
    }
    listEr.appendChild(div);
}

var btnCompare = document.getElementById('btn-compare');
btnCompare.onclick = function () {
    if (captureCount === 0) {
        Toast.init({
            "selector": ".alert-warning"
        });
        Toast.show("ท่านยังไม่ได้เลือกต่างหูที่ต้องการจะเปรียบเทียบ !!!");
        return;
    }

    var $btn = $(this).button('loading');

    var array_data = [];
    var img = $('.img-compare');
    for (var i = 0; i < img.length; i++) {
        var the_data = { ERCode: img[i].getAttribute('er_code'), ERSampleImage: img[i].src };
        array_data.push(the_data);
    }

    $.ajax({
        type: "POST",
        dataType: "json",
        crossDomain: true,
        url: "http://localhost:49331/WSRestFul.asmx/SaveCompareImage",
        data: { data: JSON.stringify(array_data) }
    }) //ajax
    .done(function (data) {
        if (data.result === 'success') {
            setTimeout(function () {
                $btn.button('reset');
                window.location = 'Compare.aspx';
            }, 1000);            
        } else {
            $btn.button('reset');
        }
    }) //done
    .fail(function (data) {
        $btn.button('reset');
        bootbox.dialog({
            title: 'Fatal Error',
            message: '<div class="alert alert-danger" role="alert"><strong>Error in connection !!!</strong></div>'
        });//boobox
    }) //fail
}